<template>
  <view class="con">
    <!-- 头部 -->
    <view class="top">
      <view class="topli flex flex_between">
        <view class="topliz">头像</view>
        <view class="topliy flex">
          <image class="topliy_1" :src="userInfo.avatarUrl" @click="chooseImageBtn"></image>
          <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
        </view>
      </view>
      <view class="topli flex flex_between">
        <view class="topliz">昵称</view>
        <view class="topliy flex" @click="showTan_1()">
          <view class="topliy_t">{{userInfo.nickName}}</view>
          <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
        </view>
      </view>
      <view class="topli flex flex_between">
        <view class="topliz">手机</view>
        <view class="topliy flex">
          <button v-if="phone==='点击获取手机号'" class="topliy_t" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">{{phone}}</button>
          <button v-else class="topliy_t" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">*******{{phone.substr(7)}}</button>
          <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
        </view>
      </view>
     <view class="topli flex flex_between">
        <view class="topliz">薇信</view>
        <view class="topliy flex" @click="showTan_2()">
          <view class="topliy_t">{{userInfo.wx}}</view>
          <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
        </view>
      </view>
    </view>
    <!-- 列表 -->
    <view class="list">
      <view class="list_li flex flex_between" @click="goIndexDetail('fwxy','用户服务协议')">
        <view class="list_liz">用户服务协议</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </view>
      <view class="list_li flex flex_between" @click="goIndexDetail('ysxy','隐私保护声明')">
        <view class="list_liz">隐私保护声明</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </view>
      <view class="list_li flex flex_between" @click="goIndexDetail('swxy','用户结算协议')">
        <view class="list_liz">用户结算协议</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </view>
      <view class="list_li flex flex_between" @click="goIndexDetail('gyxy','关于陌上未来')">
        <view class="list_liz">关于陌上未来</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </view>
      <navigator hover-class="none" :url="userInfo.zfb?'/packageA/mine/alipayResult':'/packageA/mine/alipay'" class="list_li flex flex_between">
      	<view class="list_liz">我的信息</view>
      	<image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </navigator>
      <!-- <navigator hover-class="none" url="/packageA/mine/xianYuXinXi" class="list_li flex flex_between">
      	<view class="list_liz">闲鱼信息</view>
      	<image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </navigator> -->
     <!-- <view class="list_li flex flex_between">
        <view class="list_liz">我的信息</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </view> -->
      <!-- <button open-type="contact">联系客服</button> -->
      <button open-type="contact" class="list_li flex flex_between">
        <view class="list_liz">投诉建议</view>
        <image class="list_liy" src="/static/jiant.png" mode="widthFix"></image>
      </button>
     <!-- <view class="list_li flex flex_between">
        <view class="list_liz">多多授权</view>
        <view class="list_liz" v-if="!isBind" @click="bindPage">未认证</view>
        <view class="list_liz" v-if="isBind">已认证</view>
      </view> -->
    </view>
    <view class="tuichu" @click="logout">退出登录</view>
    <view class="zhezhao" v-if="isShow_1 || isShow_2" @click="hideTan"></view>
    <!-- 修改昵称 -->
    <view class="tan" v-if="isShow_1">
      <view class="tan_title">修改昵称</view>
      <view class="tan_t flex">
        <input class="tan_input" v-model="val" placeholder="请输入新的昵称" />
      </view>
      <view class="tan_b flex flex_between">
        <view class="tan_b_d1" @click="hideTan_1">取消</view>
        <view class="tan_b_d2" @click="getUserUpdateBtn('nikename')">确认</view>
      </view>
    </view>
    <!-- 修改薇信 -->
    <view class="tan" v-if="isShow_2">
      <view class="tan_title">修改薇信</view>
      <view class="tan_t flex">
        <input class="tan_input" v-model="val" placeholder="请输入新的薇信号" />
      </view>
      <view class="tan_b flex flex_between">
        <view class="tan_b_d1" @click="hideTan_2">取消</view>
        <view class="tan_b_d2" @click="getUserUpdateBtn('wx')">确认</view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    otherSavepic, //上传图片
    getLoginUser, //获取(添加)用户信息
    getUserUpdate, //修改用户信息
    getLoginDecodephone,//解析手机号
    productIsBind //是否绑定
  } from '@/request/api.js'
  export default {
    data() {
      return {
        openid: uni.getStorageSync('openid'), //获取缓存的openid
        isShow_1: false,
        isShow_2: false,
        tag: '', //修改类型 head头像；nikename昵称；phone手机号；wx微信号
        val: '',
        userInfo: {
          avatarUrl: uni.getStorageSync('userInfo').avatarUrl, //头像
          nickName: uni.getStorageSync('userInfo').nickName, //昵称
          wx: '' //微信号
        }, //获取登录后的对象
        phone: uni.getStorageSync('userPhone') || '点击获取手机号', //手机号
        isBind:false,//是否绑定（拼多多是否授权）bind (0未绑定、1已绑定)【未认证、已认证】
        isBindReturnurl:''
      };
    },
    onLoad() {
      console.log('和我的页面保持一致：userInfo')
      console.log(uni.getStorageSync('userInfo'))

      // 获取(添加)用户信息
      getLoginUser({
        openid: this.openid,
        pid: uni.getStorageSync('pid') || ''
      }).then(res => {
        console.log('获取(添加)用户信息')
        console.log(res)
        let userInfo = uni.getStorageSync('userInfo')
        if (res.data.head) {
          userInfo.avatarUrl = res.data.head
        }
        if (res.data.nikename) {
          userInfo.nickName = res.data.nikename
        }
        if (res.data.wx) {
          userInfo.wx = res.data.wx
        }
        uni.setStorageSync('userInfo', userInfo)
        this.userInfo = uni.getStorageSync('userInfo')
      })
      // 是否绑定
      this.productIsBindFun() //是否绑定
      
    },
    methods: {
      // 是否绑定
      productIsBindFun(){
        let that = this
        productIsBind({openid:this.openid}).then(res=>{
          console.log('是否绑定')
          console.log(res)
          if(res.error_code===0){
            that.isBind = res.data.bind
            that.isBindReturnurl = res.data.returnurl
            console.log('that.isBindReturnurl')
            console.log(that.isBindReturnurl)
          }else{
            uni.showToast({
              icon: 'none',
              title: res.msg
            })
          }
        })
      },
      
      // 跳转认证页面
      bindPage(){
        uni.navigateTo({
          url:'/packageA/mine/bindPage?returnurl='+encodeURIComponent(this.isBindReturnurl)
        })
      },
      
      showTan_1() {
        this.val = this.userInfo.nickName
        console.log('点击昵称')
        this.isShow_1 = true
      },
      hideTan() {
        this.isShow_1 = false
        this.isShow_2 = false
      },
      hideTan_1() {
        this.isShow_1 = false
      },
      showTan_2() {
        this.val = this.userInfo.wx
        this.isShow_2 = true
      },
      hideTan_2() {
        this.isShow_2 = false
      },
      // 修改昵称，微信号
      getUserUpdateBtn(tag) {
        if (this.val === '') {
          uni.showToast({
            icon: 'none',
            title: '输入的内容不能为空'
          })
          return
        }
        getUserUpdate(this.openid, tag, this.val).then(res => {
          let that = this
          if (res.error_code === 0) {
            uni.showToast({
              icon: 'success',
              title: '修改成功'
            })
            that.isShow_1 = that.isShow_2 = false
            setTimeout(function() {
              that.reload()
            }, 500)
          } else {
            uni.showToast({
              icon: 'none',
              title: res.msg
            })
          }
        })
      },

      // 修改手机号
      onGetPhoneNumber(e) {
        // let _this = this
        // uni.request({
        //   url: 'https://api.weixin.qq.com/cgi-bin/stable_token',
        //   method: 'POST',
        //   data: {
        //     appid: 'wxb4a2f0381c8e1cb8',
        //     secret: '770987c23faafd7cafed3c380b0039ec',
        //     grant_type: 'client_credential'
        //   },
        //   success(res) {
        //     console.log('获取access_token信息：', res)
        //     // 保存access_token的操作，小编这里样例，就直接放在data中了
        //     _this.accessToken = res.data.access_token
        //     uni.request({
        //       url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${res.data.access_token}`,
        //       method: 'POST',
        //       data: {
        //         code: e.detail.code
        //         // openid: _this.openid (openid非必填，所以不需要先获取用户信息，再获取手机号)
        //       },
        //       success(res) {
        //         console.log('获取的用户手机号userPhone：', res)
        //         // _this.phone = res.data.phone_info.phoneNumber
        //         if (e.detail.errMsg == "getPhoneNumber:ok") {
        //           _this.phone = res.data.phone_info.phoneNumber
        //           uni.setStorageSync('userPhone', res.data.phone_info.phoneNumber)
        //         } else {
        //           console.log('用户拒绝授权或发生错误')
        //         }
        //       }
        //     })
        //   }
        // })
        if (e.detail.errMsg == "getPhoneNumber:ok") {
          // 用户同意授权获取手机号
          console.log("用户同意授权");
          console.log(e.detail)
          let detail = e.detail
          // 处理e.detail.encryptedData和e.detail.iv
          let param = {
            openid:this.openid,
            js_code:detail.code,
            encryptedData:detail.encryptedData,
            iv:detail.iv
          }
          getLoginDecodephone(param).then(res=>{
            console.log('获取用户手机号')
            // let res = JSON.parse(res)
            console.log(res)
            if(res.error_code===0){
              this.phone = res.data.phone
              uni.setStorageSync('userPhone', res.data.phone)
            }else{
              uni.showToast({
              	icon: 'none',
              	title: res.msg
              })
            }
          })

        } else {
          // 用户拒绝授权或者发生其他错误
          console.log("用户拒绝授权或发生错误");
        }
      },

      // 上传图片
      chooseImageBtn() {
        let that = this
        uni.chooseImage({
          count: 1,
          sizeType: "original",
          sourceType: ['album', 'camera'], //从相册选择
          success(res) {
            console.log('上传图片')
            console.log(res)
            uni.uploadFile({
              url: 'https://moshangweilai.herobing.com/other/savepic', //上传接口地址
              name: 'pic', //后端接收的文件参数名
              filePath: res.tempFilePaths[0], //要上传的文件路径
              formData: {},
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: (uploadFileRes) => {
                console.log('后端返回的图片')
                let res = JSON.parse(uploadFileRes.data)
                console.log(res);
                getUserUpdate(that.openid, 'head', res.data.pic).then(res => {
                  if (res.error_code === 0) {
                    uni.showToast({
                      icon: 'success',
                      title: '修改成功'
                    })
                    setTimeout(function() {
                      that.reload()
                    }, 500)
                  } else {
                    uni.showToast({
                      icon: 'none',
                      title: res.msg
                    })
                  }
                })
              },
            })
          }
        })
      },
      // 跳转"服务协议","隐私政策",'关于我们','商务合作'
      goIndexDetail(tag, title) {
        uni.navigateTo({
          url: "/packageA/index/detail?tag=" + tag + '&title=' + title
        })
      },

      // 点击退出--清除登录缓存
      logout() {
        uni.setStorageSync('isLogin', 1);
        setTimeout(function() {
          uni.navigateBack({
            delta: 1
          })
        }, 500)
      },
      // 重新刷新页面
      reload() {
        const pages = getCurrentPages()
        // 声明一个pages使用getCurrentPages方法
        const curPage = pages[pages.length - 1]
        // 声明一个当前页面
        curPage.onLoad(curPage.options) // 传入参数
        curPage.onShow()
        curPage.onReady()
      }

    }
  }
</script>

<style scoped lang="scss">
  .con {
    .list {
      width: 100%;
      height: auto;

      .list_li {
        width: 100%;
        height: 104rpx;
        border-radius: 20rpx;
        background-color: rgba(255, 255, 255, 1);
        padding: 0 30rpx;
        margin-top: 30rpx;
        box-sizing: border-box;

        .list_liz {
          color: rgba(16, 16, 16, 1);
          font-size: 28rpx;
        }

        .list_liy {
          width: 24rpx;
          height: auto;
        }
      }
    }

    .top {
      width: 100%;
      height: auto;
      border-radius: 20rpx;
      background-color: rgba(255, 255, 255, 1);
      padding: 40rpx 30rpx;
      box-sizing: border-box;
      .topli {
        width: 100%;
        height: auto;
        margin-bottom: 48rpx;

        .topliz {
          color: rgba(16, 16, 16, 1);
          font-size: 28rpx;
        }

        .topliy {
          .topliy_1 {
            width: 60rpx;
            height: 60rpx;
            border-radius: 100%;
          }

          .list_liy {
            margin-left: 14rpx;
            width: 24rpx;
            height: auto;
          }

          .topliy_t {
            color: rgba(16, 16, 16, 1);
            font-size: 28rpx;
            width: 300rpx;
            text-align: right;
          }
        }
      }

      .topli:last-child {
        margin-bottom: 0;
      }
    }

    .tuichu {
      // position: fixed;
      left: 20rpx;
      bottom: 100rpx;
      width: 710rpx;
      height: 84rpx;
      border-radius: 20rpx;
      background-color: rgba(232, 230, 230, 1);
      line-height: 84rpx;
      color: rgba(16, 16, 16, 1);
      font-size: 28rpx;
      text-align: center;
      margin-top: 40rpx;
    }

    .tan {
      margin-top: -183rpx;
    }
  }

  button.topliy_t {
    padding: 0;
    background: none !important;
    border: none !important;
  }

  button.topliy_t::after {
    border: none;
  }
</style>